package cn.huang.controller;

import cn.huang.constant.MessageConstant;
import cn.huang.entity.PageResult;
import cn.huang.entity.QueryPageBean;
import cn.huang.entity.Result;
import cn.huang.pojo.Permission;
import cn.huang.service.PermissionService;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 权限控制管理
 */
@RestController
@RequestMapping("/permission")
public class PermissionController {

    @Reference
    private PermissionService permissionService;

    //分页查询
    @RequestMapping("/findPage")
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return permissionService.pageQuery(queryPageBean);
    }

    //新增权限类型
    @RequestMapping("/add")
    public Result add(@RequestBody Permission permission){
        try {
            permissionService.add(permission);
        }catch (Exception e){
            //如果添加失败返回给页面,展示信息 新增失败
            return new Result(false, MessageConstant.ADD_PERMISSION_FAIL);
        }
        //添加成功 返回页面展示信息  新增成功
        return new Result(true,MessageConstant.ADD_PERMISSION_SUCCESS);
    }

    //删除功能
    @RequestMapping("delete")
    public Result delete(Integer id){

        try {
            permissionService.delete(id);
        }catch (RuntimeException e){
            return new Result(false,e.getMessage());
        }catch (Exception e){
            //返回给前台 让前台展示在页面上
            return new Result(false,MessageConstant.DELETE_PERMISSION_FAIL);
        }
        return new Result(true,MessageConstant.DELETE_PERMISSION_SUCCESS);
    }

    //修改功能
    @RequestMapping("/edit")
    public Result edit(@RequestBody Permission permission){
        try {
            permissionService.edit(permission);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false,MessageConstant.EDIT_PERMISSION_FAIL);
        }
        return new Result(true,MessageConstant.EDIT_PERMISSION_SUCCESS);
    }

    //回显数据,根据id查询并回显数据
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try {
           Permission permission = permissionService.findById(id);
           return new Result(true,MessageConstant.QUERY_PERMISSION_SUCCESS,permission);
        }catch (Exception e){
            e.printStackTrace();
            //服务调用失败
            return new Result(false,MessageConstant.QUERY_PERMISSION_FAIL);
        }
    }

    //查询权限项所有的数据
    @RequestMapping("/findAll")
    public Result findAll(){
        try {
            List<Permission> list = permissionService.findAll();
            return new Result(true,MessageConstant.QUERY_PERMISSION_SUCCESS,list);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_PERMISSION_FAIL);
        }
    }
}
